package com.ciwong.epaper.modules.me.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.BasePaging;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.WorkAnswers;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.DoWorkBrowerActivity;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.bean.RepeatAnswerInfo;
import com.ciwong.epaper.modules.me.adapter.StudyRecordAdapter;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.dao.db.db.StudyRecordDB;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MyWorkFileManager;
import com.ciwong.epaper.modules.me.util.UploadFileHelper;
import com.ciwong.epaper.modules.scan.bean.AnswerCard;
import com.ciwong.epaper.modules.scan.bean.EpaperQRInfo;
import com.ciwong.epaper.modules.scan.util.ScanJumpManager;
import com.ciwong.epaper.modules.viedoexplantion.util.ViedoJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.widget.BottomMenuDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.listview.PullRefreshController;
import com.ciwong.mobilelib.widget.listview.PullRefreshListView;
import com.google.gson.reflect.TypeToken;
import com.zxing.camera.CameraManager;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 我的学习记录
 *
 * @author res-qqlin
 * @version ciwong v.2.0 2015/7/24
 * @since ciwong v.2.0
 */
public class StudyRecordActivity extends BaseActivity
        implements PullRefreshController.PullRefreshListener {
    private int isOnline;
    private CWDialog dialogExt;
    private PullRefreshListView mMyWordSubmitLv;

    private StudyRecordAdapter mSubmitAdapter;

    private BottomMenuDialog bottomMenuDialog;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    /**
     * 作业列表
     */
    private ArrayList<Answer> listData = new ArrayList<Answer>();

    private int page = 1;

    private ArrayList<String> audioPaths = new ArrayList<String>();

    private static final int PAGE_SIZE = 20;

    private ImageView noDataView;

    private AnimationDrawable animationDrawable;

    private MyWorkFileManager mMyWorkFileManager;

    private TextView tvTip;

    public static final int REQUEST_CODE_TO_MARK_SCORE = 55;// 听说模考重新评测

    // private long classId;

    private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(
                        Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();

                EApplication application = (EApplication) getBaseApplication();
                Clazz clazz = application.getClazz();
                if (clazz != null) {
                    if (netInfo != null && netInfo.isAvailable()) {
                        tvTip.setVisibility(View.GONE);

                    } else {
                        tvTip.setText(R.string.connect_disable);
                        tvTip.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    };

    @Override
    protected void preCreate() {
        super.preCreate();
        Intent intent = getIntent();
        if (intent != null) {
            isOnline = intent.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, 0);
        }
    }

    @Override
    protected int setView() {
        return R.layout.activity_study_record;
    }

    @Override
    protected void findViews() {
        mMyWordSubmitLv = (PullRefreshListView) findViewById(
                R.id.my_work_submiting_listview);

        noDataView = (ImageView) findViewById(R.id.ll_no_data);
        animationDrawable = (AnimationDrawable) noDataView.getDrawable();
        tvTip = (TextView) findViewById(R.id.work_submit_tip);
    }

    /**
     * 注册网络监听广播
     */
    private void registerNetReceiver() {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(myNetReceiver, mFilter);
    }

    /**
     * 解除网络监听广播
     */
    private void unregisterNetReceiver() {
        if (myNetReceiver != null) {
            unregisterReceiver(myNetReceiver);
        }
    }

    @Override
    protected void initEvent() {
        registerNetReceiver();

        tvTip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getString(R.string.no_class_tip)
                        .equals(tvTip.getText().toString())) {
                    MeJumpManager.jumpToJoinClassActivity(R.string.go_back,
                            StudyRecordActivity.this, 0, 0);
                }
            }
        });

        mMyWordSubmitLv.setPullRefreshEnable(true);
        mMyWordSubmitLv.setPullLoadEnable(true);
        mMyWordSubmitLv.setPullRefreshListener(this);
        mMyWordSubmitLv.hideFooter();

        // classId = CWSys.getSharedLong(NConstants.KEY_SELECTED_CLASS_ID
        // + getUserInfoBase().getUserId(), 0);
        // tvTip.setText(R.string.no_add_class_tip);
        // tvTip.setVisibility(classId <= 0 ? View.VISIBLE : View.GONE);

        EventBus.getDefault().register(this);
        // 列表点击事件
        mMyWordSubmitLv
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Answer answer = (Answer) parent
                                .getItemAtPosition(position);
                        if (answer == null) {
                            return;
                        }

                        int moduleId = answer.getModuleId();
                        if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST
                                || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT
                                || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN
                                || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                            jumpByTypeCondition(answer);
                        }
                    }
                });
    }

    @Override
    protected void init() {
        if (isOnline == 0) {
            setTitleText(R.string.answer);
        } else {
            setTitleText(R.string.learn_record);
        }
        mMyWorkFileManager = MyWorkFileManager.getInstance();
        mSubmitAdapter = new StudyRecordAdapter(this, listData);
        mMyWordSubmitLv.setAdapter(mSubmitAdapter);

        EApplication application = (EApplication) getBaseApplication();
        Clazz clazz = application.getClazz();
        tvTip.setText(R.string.no_class_tip);
        tvTip.setVisibility(clazz == null ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void loadData() {
        loadLocalData();
    }


    @Override
    protected void onResume() {
        super.onResume();
//        page = 1;
//        loadLocalData();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterNetReceiver();
    }

    /**
     * 加载本地数据后更新网络数据
     */
    private void loadLocalData() {
        showMiddleProgressBar(getTitleText());
        MeDao.getInstance().queryMyStudyRecord(isOnline, new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(final Object data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        List<Answer> tempList = (List<Answer>) data;
                        if (tempList != null && !tempList.isEmpty()) {
                            Collections.sort(tempList, new Answer.AnswerComparator());

                            List<Answer> addList = new ArrayList<Answer>();
                            for (Answer answer : tempList) {

                                //版本升级清除本地听说模考的失败记录
                                if (answer.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
                                    StudyRecordDB.deleteDataById(answer.get_id() + "");
                                } else if (answer.getModuleId() != ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
                                    addList.add(answer);
                                }
                            }

                            listData.clear();
                            listData.addAll(addList);

                            noDataView.setVisibility(View.GONE);
                            animationDrawable.stop();
                            mSubmitAdapter.notifyDataSetChanged();
                        } else {
                            noDataView.setVisibility(View.VISIBLE);
                            animationDrawable.start();
                        }
                        reFillCompletedList();
                    }
                });

            }
        });
    }

    private void handLocalWorkFile(final Answer answer) { //本地跟读作业被删除，重新下载。
        //下载资源
        DownLoadInfo downLoadInfo = answerToDownLoadInfo(answer);
        showCricleProgress(R.string.loading_work);

        mMyWorkFileManager.addWorkToDownLoad(downLoadInfo, new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
            }


            @Override
            public void failed(Object data) {
                hideCricleProgress();
            }

            @Override
            public void success(Object data) {

                hideCricleProgress();
                //下载完重新自动打开
                jumpByTypeCondition(answer);
            }

        });
    }

    private DownLoadInfo answerToDownLoadInfo(Answer answer) {
        DownLoadInfo dInfo = new DownLoadInfo();
        dInfo.setBookId(answer.getPackageId());
        dInfo.setChapterId(answer.getcId());
        dInfo.setUrl(answer.getDoWorkPackageUrl());
        dInfo.setSavePath(
                FileUtil.getSavePathByUrl(StudyRecordActivity.this, answer.getDoWorkPackageUrl()));
        dInfo.setStatus(DownloadStatus.STATUS_LOADING);
        return dInfo;
    }

    public void onEventMainThread(Answer answer) {
        if (answer.getSubmitStatus() == Answer.SubmitStatus.WORK_SUBMIT_SUCCUED) {
            listData.remove(answer);
            mSubmitAdapter.notifyDataSetChanged();
            reFillCompletedList();
            return;
        }
        int indexOf = listData.indexOf(answer);
        if (indexOf >= 0) {
            Answer a = listData.get(indexOf);
            a.setSubmitStatus(answer.getSubmitStatus());
            a.setProgress(answer.getProgress());
            a.setLogInfo(answer.getLogInfo());
            a.setWorkAnswers(answer.getWorkAnswers());

            mSubmitAdapter.notifyDataSetChanged();
        }
    }

    public void getSynTextImageUrlAndJumpScanImage(final Answer answer) {
        String pUrl = "";
        pUrl = answer.getDoWorkPackageUrl();
        if (pUrl == null) {
            pUrl = answer.getDoWorkLocalPath();
        }
        String name = pUrl.substring(pUrl.lastIndexOf("/") + 1,
                pUrl.lastIndexOf("."));

        final ArrayList<String> imagePaths = new ArrayList<String>();
        Type type = new TypeToken<List<AnswerCard>>() {
        }.getType();
        // String path = NSystem.getAnswersPath() + File.separator +(name) +
        // File.separator + NSystem.USER_ANSWER;
        String path = ESystem.getAnswersUserAnswerPath(name);
        final String prePath = EConstants.FILE_PREFIX
                + ESystem.getAnswersUuidPath(name) + File.separator;
        EpaperDao.getInstance().getSerializableObjects(path, type,
                new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void success(final Object data) {
                        List<AnswerCard> b = (List<AnswerCard>) data;
                        for (int i = 0; i < b.size(); i++) {
                            AnswerCard answerCards = b.get(i);
                            imagePaths.add(prePath + answerCards.getContenet());
                        }
                        if (imagePaths.size() > 0) {
                            BaseJumpManager.jumpToScanImage(
                                    StudyRecordActivity.this, R.string.go_back,
                                    imagePaths, 0);
                        } else {
                            handLocalWorkFile(answer);
                            // showToastError(R.string.no_resources);
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void failed(Object data) {
                        handLocalWorkFile(answer);
                        // showToastError(R.string.no_resources);
                    }
                });
    }

    /**
     * @param answer
     */
    private void jumpByTypeCondition(final Answer answer) {
        ArrayList<String> str = new ArrayList<String>();


        int workStatus = answer.getWorkStatus();
        int submitStatus = answer.getSubmitStatus();
        int moduleId = answer.getModuleId();


        if (workStatus == Answer.WorkStatus.WORK_STATUS_UNKNOWN_CARD) {// 无法识别答题卡
            str.add(getString(R.string.look_answer_card));
            str.add(getString(R.string.camera_again));

            ScanJumpManager.jumpCature(StudyRecordActivity.this,
                    CameraManager.CaptureMode.ANSWERCARD, answer);
        } else if (submitStatus == Answer.SubmitStatus.WORK_SUBMITING) { // 正在提交
            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                str.add(getString(R.string.look_answer_card));
                getSynTextImageUrlAndJumpScanImage(answer);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT) {
                str.add(getString(R.string.repeat_audio));
                getSynReadUrl(answer);
            }
        } else if (submitStatus != Answer.SubmitStatus.WORK_SUBMIT_SUCCUED) { // 提交失败
            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                str.add(getString(R.string.look_answer_card));
                getSynTextImageUrlAndJumpScanImage(answer);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT) {
                str.add(getString(R.string.repeat_audio));
//                getSynReadUrl(answer);
                showBottomMenuDialog(answer);
                return;
            }
            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM && submitStatus == Answer.SubmitStatus.WORK_NO_SCORE_FAILE) {
                str.add(getString(R.string.make_score_again));
                //重新评测，直接跳转到重评页面
                Module module = new Module();
                DownLoadInfo downLoadInfo = new DownLoadInfo();
                downLoadInfo.setBookId(answer.getPackageId());
                downLoadInfo.setChapterId(answer.getcId());
                ModuleInfo moduleInfo = new ModuleInfo();
                moduleInfo.setModuleId(answer.getModuleId());
                moduleInfo.setcId(answer.getcId());
                module.setModuleInfo(moduleInfo);
                ModuleContent moduleContent = new ModuleContent();
                moduleContent.setResourceName(answer.getResourceName());
                moduleContent.setResourceType(answer.getResourceType());
                moduleContent.setVersionId(answer.getVersionId());
                moduleContent.setParentVersionId(answer.getParentVersionId());
                ArrayList<ModuleContent> moduleContents = new ArrayList<ModuleContent>();
                moduleContents.add(moduleContent);
                module.setResourceList(moduleContents);
//                EpaperJumpManager.jumpToListenSpeakWork(R.string.go_back,
//                        StudyRecordActivity.this, answer.getWorkId(),
//                        downLoadInfo, module, 0, answer.getJsonVersion(), "", 0,
//                        answer, REQUEST_CODE_TO_MARK_SCORE,answer.getWorkType());
//                retryMarkScore(answer.getWorkId(),downLoadInfo,module,0,answer);

                return;
            } else {
                showBottomMenuDialog(answer);
                return;
            }
        } else { // 作业是提交成功的
            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
//                str.add(getString(
//                        (workStatus == Answer.WorkStatus.WORK_STATUS_CHECK
//                                && answer.getActualScore() < answer.getWorkScore())
//                                                ? R.string.my_wrong_question
//                                                : R.string.look_answer_card));

                String typeStr = getString((workStatus == Answer.WorkStatus.WORK_STATUS_CHECK
                        && answer.getActualScore() < answer
                        .getWorkScore())
                        ? R.string.my_wrong_question
                        : R.string.look_answer_card);

                if (typeStr.endsWith(getString(R.string.my_wrong_question))) {
//                    R.string.my_wrong_question
                    MeJumpManager.jumpToMyWrongQues(StudyRecordActivity.this, R.string.go_back, answer);
                } else {
//                    R.string.look_answer_card
                    getSynTextImageUrlAndJumpScanImage(answer);
                }

            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT) {
                str.add(getString(R.string.repeat_audio));
                getSynReadUrl(answer);
            }

        }


        if ((moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN ||
                moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER ||
                moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM)
                && !str.contains(getString(R.string.make_score_again)))//moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM  ||
        {

            str.add(getString(R.string.look_detail));
            String path = ESystem.getPackagesMainJsonPath(answer.getPackageId(), answer.getcId());

            if (new File(path).exists()) {
                String name = "";
                String pUrl = answer.getDoWorkPackageUrl();
                if (TextUtils.isEmpty(pUrl) || !pUrl.startsWith("http")) {
                    if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
                        //如果是听说模考  zip包的路径是空的  做兼容处理//听说模考单独处理
                        //非听说模考资源 还是有zip包路径
                        DownLoadInfo downLoadInfo = new DownLoadInfo();
                        downLoadInfo.setBookId(answer.getPackageId());
                        downLoadInfo.setChapterId(answer.getcId());
                        downLoadInfo.setChapterName(answer.getResourceName());

                        Module module = new Module();
                        ModuleInfo moduleInfo = new ModuleInfo();
                        moduleInfo.setModuleId(answer.getModuleId());
                        moduleInfo.setcId(answer.getcId());
                        module.setModuleInfo(moduleInfo);
                        ModuleContent moduleContent = new ModuleContent();
                        //听说模考资源json没有暂时未空
                        //moduleContent.setResourceFile();
                        moduleContent.setResourceName(answer.getResourceName());
                        moduleContent.setResourceType(answer.getResourceType());
                        moduleContent.setVersionId(answer.getVersionId());
                        moduleContent.setParentVersionId(
                                answer.getParentVersionId());
                        ArrayList<ModuleContent> moduleContents = new ArrayList<ModuleContent>();

                        moduleContents.add(moduleContent);
                        module.setResourceList(moduleContents);
                        //直接跳转到新的学习记录页面
                        EpaperJumpManager.jumpToNewLsWorkRecord(answer.getComment(), R.string.go_back, StudyRecordActivity.this, downLoadInfo, module, answer.getCheckedResource(), answer.getDoWorkId(), answer.getResourceName(), workStatus, 0);

                        return;
                    } else {
                        pUrl = answer.getDoWorkLocalPath();
                        if (pUrl.endsWith(".zip")) {
                            name = pUrl.substring(pUrl.lastIndexOf("/") + 1,
                                    pUrl.lastIndexOf("."));
                        } else {
                            name = pUrl.substring(pUrl.lastIndexOf("/") + 1);
                        }
                    }

                } else {//这里要对新的听说模考进行处理  因为没有了ZIP包
                    name = pUrl.substring(pUrl.lastIndexOf("/") + 1,
                            pUrl.lastIndexOf("."));
                }

                String resourcePath = ESystem.getAnswersPath()
                        + File.separator + name + File.separator
                        + ESystem.MAIN;
                if (new File(resourcePath).exists()) {
                    DownLoadInfo downLoadInfo = new DownLoadInfo();
                    downLoadInfo.setBookId(answer.getPackageId());
                    downLoadInfo.setChapterId(answer.getcId());
                    downLoadInfo.setChapterName(answer.getResourceName());


                    Module module = new Module();
                    ModuleInfo moduleInfo = new ModuleInfo();
                    moduleInfo.setModuleId(answer.getModuleId());
                    moduleInfo.setcId(answer.getcId());
                    module.setModuleInfo(moduleInfo);
                    ModuleContent moduleContent = new ModuleContent();
                    moduleContent.setResourceFile(resourcePath);
                    moduleContent.setResourceName(answer.getResourceName());
                    moduleContent.setResourceType(answer.getResourceType());
                    moduleContent.setVersionId(answer.getVersionId());
                    moduleContent.setParentVersionId(
                            answer.getParentVersionId());
                    ArrayList<ModuleContent> moduleContents = new ArrayList<ModuleContent>();
                    moduleContents.add(moduleContent);
                    module.setResourceList(moduleContents);

                    if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN ||
                            moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                        loadMainData(downLoadInfo, answer);
                    } else {
                        EpaperJumpManager.jumpToDoWorkBrowser(answer, R.string.go_back, StudyRecordActivity.this, DoWorkBrowerActivity.BrowerJumpType.TYPE_LS_ANSWER, downLoadInfo, module, 0, name, answer.getDoWorkId(), answer.getCheckedResource(), answer.getResourceName());
                    }
                } else {
                    if (TextUtils.isEmpty(answer.getDoWorkPackageUrl())) {
                        showToastError(R.string.no_resources);
                    } else {
                        handLocalWorkFile(answer);
                    }

                }


            } else {
                if (NetworkUtils.isWifiOnline()) {
                    startDownLoad(answer);

                } else if (NetworkUtils.isOnline()) {

                    show4GTipsDialog(StudyRecordActivity.this, answer);

                } else {
                    CWToast.makeText(StudyRecordActivity.this,
                            R.string.connect_disable, Toast.LENGTH_LONG,
                            true).setToastType(CWToast.TOAST_TYPE_ERROR)
                            .show();
                }


            }
        }

    }


    /**
     * 显示是否在wifi对话框
     *
     * @param act Activity
     * @param
     */
    public void show4GTipsDialog(final Activity act, final Answer answer) {
        final CWDialog wifiDialog = new CWDialog(act);
        wifiDialog.setMessage(R.string.is_wifi_hint);
        wifiDialog.setPositiveButton(R.string.continuation_download,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface interDialog,
                                        int which) {
                        startDownLoad(answer);
                        wifiDialog.dismiss();
                    }
                });
        wifiDialog.setNegativeButton(R.string.cancel_download, null);
        wifiDialog.setCanceledOnTouchOutside(true);
        wifiDialog.show();
    }


    private void startDownLoad(Answer answer) {

        showMiddleProgressBar(getTitleText());
        DownLoadInfo info = new DownLoadInfo();
        info.setBookId(answer.getPackageId());
        info.setChapterId(answer.getcId());
        info.setIsEqualsWork(true);
        if (DownLoad.getInstance().getCurrentBean(info) == null) {
            EpaperDao.getInstance().getCatalogueInfo(
                    answer.getPackageId(), answer.getcId(), new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                        @Override
                        public void failed(int errorCode,
                                           Object data) {
                            super.failed(errorCode, data);
                            hideMiddleProgressBar();
                            DialogUtil.showFailedToastByErrorType(StudyRecordActivity.this, data);
                        }

                        @Override
                        public void failed(Object data) {
                            super.failed(data);
                            hideMiddleProgressBar();
                            DialogUtil.showFailedToastByErrorType(StudyRecordActivity.this, data);


                        }

                        @Override
                        public void success(Object data) {
                            hideMiddleProgressBar();
                            EpaperQRInfo newspaperQRInfo = (EpaperQRInfo) data;
                            String url = newspaperQRInfo
                                    .getDownLoadUrl();
                            if (TextUtils.isEmpty(url)) {
                                showToastError(R.string.no_download_url);
                            } else {
                                DownLoadInfo downLoadInfo = new DownLoadInfo();
                                downLoadInfo
                                        .setBookId(newspaperQRInfo
                                                .getPackageId());
                                downLoadInfo
                                        .setBookName(newspaperQRInfo
                                                .getPackageName());
                                downLoadInfo
                                        .setIconUrl(newspaperQRInfo
                                                .getPackageCover());
                                downLoadInfo.setChapterId(
                                        newspaperQRInfo.getcId());
                                downLoadInfo.setChapterName(newspaperQRInfo.getcName());
                                downLoadInfo.setUrl(url);
                                downLoadInfo.setSavePath(FileUtil
                                        .getSavePathByUrl(StudyRecordActivity.this, url));
                                downLoadInfo.setStatus(
                                        DownloadStatus.STATUS_LOADING);
                                String fileSize = newspaperQRInfo
                                        .getFileSize();
                                if (!TextUtils.isEmpty(fileSize)
                                        && fileSize.contains(" ")) {
                                    downLoadInfo.setSize(
                                            fileSize.split(" ")[0]);
                                }

                                if (DialogUtil.sdIsFullForDownload(StudyRecordActivity.this,
                                        downLoadInfo)) {
                                    DialogUtil.showSdFullDialog(
                                            StudyRecordActivity.this,
                                            downLoadInfo.getSize());
                                    return;
                                }
                                DownLoad.getInstance()
                                        .addTask(downLoadInfo);
                                MeJumpManager.jumpToLoadingFiles(
                                        StudyRecordActivity.this,
                                        R.string.go_back);
                            }
                        }
                    });
        } else {
            hideMiddleProgressBar();
            MeJumpManager.jumpToLoadingFiles(
                    StudyRecordActivity.this, R.string.go_back);
        }


    }

    /**
     * 重新评测  取失败记录列表
     * 进来说明学习记录不为空 userAnswerseList!=null
     */
    protected void retryMarkScore(String workId, final DownLoadInfo downLoadInfo, final Module module,
                                  final int position, final Answer localAnswer) {
        final String saveUUid = CWSys.getSharedString(ListenSpeakUtil.getUuidSaveKey(downLoadInfo, module, position, workId, 0), null);
        if (null == saveUUid) {
            showToastError(R.string.str_find_retry_res_fail);
            return;
        }

        StudyRecordDB.deleteDataById(localAnswer.get_id() + "");
        onResume();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (resultCode == RESULT_OK) {
//            if (requestCode == REQUEST_CODE_TO_MARK_SCORE)
            {
                page = 1;
                loadLocalData();
            }
        }
    }

    private void getSynReadUrl(final Answer answer) {
        String pUrl = "";
        pUrl = answer.getDoWorkPackageUrl();
        if (pUrl == null) {
            pUrl = answer.getDoWorkLocalPath();
        }
        String name = pUrl.substring(pUrl.lastIndexOf("/") + 1,
                pUrl.lastIndexOf("."));

        // mBtn = btn;
        // mCurrentAnswer = answer;

        Type type = new TypeToken<List<WorkAnswers<RepeatAnswerInfo>>>() {
        }.getType();
        String path = ESystem.getAnswersUserAnswerPath(name);
        audioPaths.clear();
        final String prePath = EConstants.FILE_PREFIX
                + ESystem.getAnswersUuidPath(name) + File.separator;
        EpaperDao.getInstance().getSerializableObjects(path, type,
                new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void success(final Object data) {
                        List<WorkAnswers<RepeatAnswerInfo>> b = (List<WorkAnswers<RepeatAnswerInfo>>) data;
                        for (int i = 0; i < b.size(); i++) {
                            WorkAnswers<RepeatAnswerInfo> workAnswers = b
                                    .get(i);
                            List<RepeatAnswerInfo> aInfos = workAnswers
                                    .getAnswers();
                            for (int j = 0; j < aInfos.size(); j++) {
                                RepeatAnswerInfo repeatAnswerInfo = aInfos
                                        .get(j);
                                audioPaths.add(prePath
                                        + repeatAnswerInfo.getAudioUrl());
                            }
                        }

                        Module module = new Module();

                        ModuleInfo moduleInfo = new ModuleInfo();
                        moduleInfo.setModuleId(answer.getModuleId());
                        moduleInfo.setcId(answer.getcId());
                        module.setModuleInfo(moduleInfo);
                        ModuleContent c = new ModuleContent();
                        c.setResourceName(answer.getResourceName());
                        c.setResourceType(answer.getResourceType());
                        c.setVersionId(answer.getVersionId());
                        c.setParentVersionId(answer.getParentVersionId());
                        ArrayList<ModuleContent> mList = new ArrayList<ModuleContent>();
                        mList.add(c);
                        module.setResourceList(mList);

                        EpaperJumpManager.jumpToDictaion(answer, R.string.go_back,
                                StudyRecordActivity.this, module, audioPaths);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        handLocalWorkFile(answer);
                    }

                    @Override
                    public void failed(Object data) {
                        handLocalWorkFile(answer);

                    }
                });
    }

    /**
     * 重新查询并填充已完成的作业列表
     */
    private void reFillCompletedList() {
        MeDao.getInstance().getMyStudyRecord(EApplication.BRAND_ID, isOnline,
                page, PAGE_SIZE, new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(Object data) {
                        hideMiddleProgressBar();
                        mMyWordSubmitLv.stopLoadMore();
                        mMyWordSubmitLv.stopRefresh();
                        if (data instanceof AuthFailureError) {
                            EJumpManager.jumpToDialogActivity(
                                    StudyRecordActivity.this);
                        }
                    }

                    @Override
                    public void success(Object data) {
                        BasePaging<Answer> b = (BasePaging<Answer>) data;
                        final List<Answer> results = (ArrayList<Answer>) b
                                .getPageList();

                        //先装入本地数据库查询出来的，包括提交失败的的记录
                        CopyOnWriteArrayList<Answer> tempList = new CopyOnWriteArrayList<Answer>();
                        tempList.addAll(listData);


                        if (results != null && !results.isEmpty()) {
                            for (Answer answer : results) {
                                answer.setSubmitStatus(
                                        Answer.SubmitStatus.WORK_SUBMIT_SUCCUED);
                            }

                            //移除本地数据库记录中成功的记录，只要失败的记录，后面结合服务器数据库查询的成功记录
                            for (Iterator iterator = tempList.iterator(); iterator.hasNext(); ) {
                                Answer answer = (Answer) iterator.next();
                                if (answer.getSubmitStatus() == Answer.SubmitStatus.WORK_SUBMIT_SUCCUED) {
                                    tempList.remove(answer);
                                }
                            }

                            tempList.addAll(results);
                        }


                        //移除视频讲解的记录
                        List<Answer> addList = new ArrayList<Answer>();
                        for (Answer answer : tempList) {
                            if (answer.getModuleId() != ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
                                addList.add(answer);
                            }
                        }

                        listData.clear();
                        listData.addAll(addList);

                        mSubmitAdapter.notifyDataSetChanged();
                        if (tempList.isEmpty()) {
                            noDataView.setVisibility(View.VISIBLE);
                            animationDrawable.start();
                        } else {
                            noDataView.setVisibility(View.GONE);
                            animationDrawable.stop();
                        }
                        ThreadTask.getInstance().executorDBThread(new Runnable() {
                            @Override
                            public void run() {
                                StudyRecordDB.reFillCompeletedList(isOnline,
                                        results);
                            }
                        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
                        mMyWordSubmitLv.stopRefresh();
                        mMyWordSubmitLv.stopLoadMore();
                        mMyWordSubmitLv.setPullLoadEnable(
                                b.getPage() < b.getPageCount());
                        hideMiddleProgressBar();
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        showToastError(errorCode, data);
                        mMyWordSubmitLv.stopRefresh();
                        mMyWordSubmitLv.stopLoadMore();
                        hideMiddleProgressBar();
                    }
                });
    }

    @Override
    public void onRefresh() {
        page = 1;
        loadLocalData();
    }

    @Override
    public void onLoadMore() {
        page++;
        MeDao.getInstance().getMyStudyRecord(EApplication.BRAND_ID, isOnline,
                page, PAGE_SIZE, new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(Object data) {
                        page--;
                        mMyWordSubmitLv.stopRefresh();
                        mMyWordSubmitLv.stopLoadMore();
                    }

                    @Override
                    public void success(Object data) {
                        BasePaging<Answer> b = (BasePaging<Answer>) data;
                        final List<Answer> results = (ArrayList<Answer>) b
                                .getPageList();
                        for (Answer answer : results) {
                            answer.setSubmitStatus(
                                    Answer.SubmitStatus.WORK_SUBMIT_SUCCUED);
                        }
                        noDataView.setVisibility(View.GONE);
                        animationDrawable.stop();

                        List<Answer> addList = new ArrayList<Answer>();

                        for (Answer answer : results) {
                            if (answer.getModuleId() != ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
                                addList.add(answer);
                            }
                        }


                        listData.addAll(addList);
                        mSubmitAdapter.notifyDataSetChanged();

                        mMyWordSubmitLv.stopRefresh();
                        mMyWordSubmitLv.stopLoadMore();
                        mMyWordSubmitLv
                                .setPullLoadEnable(results.size() >= PAGE_SIZE);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        page--;
                        showToastError(errorCode, data);
                        mMyWordSubmitLv.stopRefresh();
                        mMyWordSubmitLv.stopLoadMore();
                    }
                });
    }


    /**
     * 弹出底部框
     *
     * @param answer
     */
    private void showBottomMenuDialog(Answer answer) {
        bottomMenuDialog = new BottomMenuDialog(this);
        bottomMenuDialog
                .setBtnTextColor(getResources().getColor(R.color.green));
        bottomMenuDialog
                .setLastBtnTextColor(getResources().getColor(R.color.gray));

        ArrayList<String> str = new ArrayList<String>();
        str.add(getString(R.string.submit_again));
        str.add(getString(android.R.string.cancel));
        bottomMenuDialog.setMenuTextList(str);

        ArrayList<View.OnClickListener> listeners = new ArrayList<View.OnClickListener>();
        BottomClickListener bottomClickListener = new BottomClickListener(
                answer);
        for (int i = 0; i < str.size(); i++) {
            listeners.add(bottomClickListener);
        }

        bottomMenuDialog.setMenuOnClickListeners(listeners);
        bottomMenuDialog.show();
    }


    class BottomClickListener implements View.OnClickListener {
        private Answer answer;

        public BottomClickListener(Answer answer) {
            this.answer = answer;
        }

        @Override
        public void onClick(View v) {
            String str = ((Button) v).getText().toString();
            if (getString(R.string.submit_again).equals(str)) { // 重新提交
                final String path = answer.getDoWorkLocalPath();

                String localPath = "";
                if (!TextUtils.isEmpty(path) && !path.endsWith(".zip")) {// 说明是uuid
                    localPath = ESystem.getAnswersUuidPathNoCreate(path);
                } else {
                    localPath = path;
                }
                if (!TextUtils.isEmpty(localPath)) {
                    ThreadTask.getInstance().executorOtherThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!path.endsWith(".zip")) {
                                if (new File(ESystem.getAnswersUuidPathNoCreate(path)).exists()) {
                                    String zipFile = EpaperDao.getInstance()
                                            .generateZipFile(path);
                                    if (!TextUtils.isEmpty(zipFile)) {
                                        answer.setDoWorkLocalPath(zipFile);
                                    }
                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            showToastError(
                                                    R.string.file_no_exist);
                                        }
                                    });
                                    return;
                                }
                            } else if (!new File(path).exists()) {
                                String uuid = path.substring(
                                        path.lastIndexOf("/") + 1,
                                        path.lastIndexOf("."));
                                String zipFile = EpaperDao.getInstance()
                                        .generateZipFile(uuid);
                                if (!TextUtils.isEmpty(zipFile)) {
                                    answer.setDoWorkLocalPath(zipFile);
                                }
                            }
                            if (TextUtils.isEmpty(answer.getDoWorkPackageUrl())) {
                                answer.setSubmitStatus(
                                        Answer.SubmitStatus.WORK_SUBMITING);
                            }

                            if (answer.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {
                                answer.setResourceType(ModuleContent.ResourceType.RESOURCE_TYPE_VIDEO_EXPLAIN);

                            } else if (answer.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) {
                                answer.setResourceType(ModuleContent.ResourceType.RESOURCE_TYPE_VIDEO_EXPLAIN_NEW);
                            } else if (answer.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                                answer.setResourceType(ModuleContent.ResourceType.RESOURCE_TYPE_ONLINE_ANSWER);
                            }

                            UploadFileHelper.getInstance().submitAnswer(answer,

                                    getUserInfoBase().getUserId(), new BaseExtCallBack(StudyRecordActivity.this, String.valueOf(getUserInfoBase().getUserId())) {


                                        @Override
                                        public void failed(int errorCode, Object data) {
                                            super.failed(errorCode, data);
                                        }

                                        @Override
                                        public void failed(Object data) {
                                        }

                                        @Override
                                        public void success(Object data) {//重交成功，本地做相应处理
                                            Log.d("ciwong", "#######重交成功##########");
                                        }

                                    }, mHandler, answer.getModuleId());

                        }
                    }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
                } else {
                    //
                    showToastError(R.string.file_no_exist + "1");
                }
            }

            bottomMenuDialog.dismiss();
        }
    }


    protected void loadMainData(final DownLoadInfo downLoadInfo, final Answer answer) {
        String path = ESystem.getPackagesMainJsonPath(downLoadInfo.getBookId(),
                downLoadInfo.getChapterId());
        EpaperDao.getInstance().getSerializableObjects(path, Main.class,
                new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(Object data) {
                        CWToast.makeText(StudyRecordActivity.this, (int) data,
                                Toast.LENGTH_LONG, true)
                                .setToastType(CWToast.TOAST_TYPE_ERROR).show();
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data) {
                        Main main = (Main) data;
                        getCatalogueFile(main.getCatalogueFile(),
                                main.getJsonVersion(), downLoadInfo, answer);
                    }
                });
    }


    /**
     * 获取目录内容信息
     *
     * @param path        目录内容信息地址
     * @param jsonVersion
     */
    private void getCatalogueFile(String path, final String jsonVersion, final DownLoadInfo downLoadInfo, final Answer answer) {
        path = ESystem.getPackagesPath(StudyRecordActivity.this) + File.separator + path;
        Type responseType = new TypeToken<List<Module>>() {
        }.getType();
        EpaperDao.getInstance().getSerializableObjects(path, responseType,
                new BaseExtCallBack(StudyRecordActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(Object data) {
                        CWToast.makeText(StudyRecordActivity.this, (int) data,
                                Toast.LENGTH_LONG, true)
                                .setToastType(CWToast.TOAST_TYPE_ERROR).show();
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data) {
                        List<Module> modules = (List<Module>) data;
                        if (modules == null) {
                            return;
                        }

                        int position = 0;

                        if (modules.size() > 0) {
                            //学习记录 视频讲解不再打开  应该没有老的视频讲解的数据了 理论上服务器端的与视频讲解学习记录的数据应该清理干净
                            //为了保险 本地对请求回来的数据和本地数据做了一次老的视频讲解的数据过滤
                            if (answer.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN) {

                                answer.getVersionId();
                                answer.getParentVersionId();
                                Module module = modules.get(0);

                                a:
                                for (int i = 0; i < modules.size(); i++) {
                                    module = modules.get(i);
                                    for (int j = 0; j < module.getResourceList().size(); j++) {
                                        if (module.getResourceList().get(j).getVersionId().equals(answer.getVersionId()) && module.getResourceList().get(j).getParentVersionId().equals(answer.getParentVersionId())) {
                                            module = modules.get(i);
                                            position = j;
                                            break a;
                                        }
                                    }
                                }
                                int serviceId = answer.getWorkType();

                                if (serviceId == 0) {
                                    //说明是新加字段前的记录，应该不做权限过滤
                                    serviceId = EpaperConstant.DEFAULT_OLD_SERVICE_ID;

                                }
                                //老的视频讲解 不做任何操作
                                //ViedoJumpManager.jumpToCordovaWebViewTestActivity(R.string.go_back,StudyRecordActivity.this, EpaperConstant.H5_JUMP_TYPE_VIDEO_EXPLAIN,null,downLoadInfo,module,position,answer,answer.getDoWorkId(),answer.getComment(),answer.getResourceName(),EpaperConstant.H5_PAGE_TYPE_STUDY_RECORD,serviceId,null);

                            } else if (answer.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                                Module module = modules.get(0);

                                a:
                                for (int i = 0; i < modules.size(); i++) {
                                    module = modules.get(i);

                                    for (int j = 0; j < module.getResourceList().size(); j++) {
                                        if (module.getResourceList().get(j).getVersionId().equals(answer.getVersionId()) && module.getResourceList().get(j).getParentVersionId().equals(answer.getParentVersionId())) {
                                            module = modules.get(i);
                                            position = j;
                                            break a;
                                        }
                                    }
                                }

                                int serviceId = answer.getWorkType();
                                if (serviceId == 0) {
                                    //说明是新加字段前的记录，应该不做权限过滤
                                    serviceId = EpaperConstant.DEFAULT_OLD_SERVICE_ID;

                                }
                                Log.d("ciwong", "#######MODULE_ID_ONLINE_ANSWER##########");
                                ViedoJumpManager.jumpToCordovaWebViewTestActivity(R.string.go_back, StudyRecordActivity.this, EpaperConstant.H5_JUMP_TYPE_ONLINE_ANSWER, null, downLoadInfo, module, position, answer, answer.getDoWorkId(), answer.getComment(), answer.getResourceName(), EpaperConstant.H5_PAGE_TYPE_STUDY_RECORD, serviceId, null, null, RequestCode.HomeWorkFragmentResquestCode.REQ_ONLINE_ANSWER);
                            }
                        }
                    }
                });
    }

}